package com.ambulance.project.biz.controller.common;

import com.ambulance.framework.MyRedisTemplate;
import com.ambulance.framework.web.domain.AjaxResult;
import com.ambulance.project.biz.dto.DeviceStatusDto;
import com.ambulance.project.biz.dto.NetWorkDto;
import com.ambulance.project.biz.entity.Car;
import com.ambulance.project.biz.entity.CarDevice;
import com.ambulance.project.biz.entity.Dispatch;
import com.ambulance.project.biz.service.CarDeviceService;
import com.ambulance.project.biz.service.CarService;
import com.ambulance.project.manager.utils.DoctorAndNurseCommonUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;
import java.util.Random;

/**
 * @Author RXL
 * @Date 2020/6/24 14:54
 * @Version 1.0
 */
@Api(tags = "多端共用-网络信号")
@RestController
@RequestMapping(value = "/common/v1/NetWork", method = RequestMethod.POST)
public class NetWorkController {

    @Autowired
    private DoctorAndNurseCommonUtil padCommonUtil;
    @Autowired
    private CarDeviceService carDeviceService;

    @Autowired
    private CarService carService;
    @Autowired
    private MyRedisTemplate myRedisTemplate;

    @ApiOperation(value = "网络信号", notes = "网络信号", produces = "application/json")
    @ApiResponses({
            @ApiResponse(code = 200, response = NetWorkDto.class, message = "响应")
    })
    @RequestMapping(value = "/info")
    public AjaxResult netWorkInfo(@RequestParam(value = "catId", required = false, defaultValue = "0") Integer carId) {
        if (carId == 0) {
            // todo 大屏和pad网络信号
            Dispatch dispatch = padCommonUtil.getDispatch();
            carId = dispatch.getCarID();
        }

        NetWorkDto netWorkDto = getNetWorkDto(carId);
        return AjaxResult.success(netWorkDto);
    }

    @ApiOperation(value = "设备在线状态", notes = "设备在线状态", produces = "application/json")
    @ApiResponses({
            @ApiResponse(code = 200, response = DeviceStatusDto.class, message = "响应")
    })
    @RequestMapping(value = "/device/online")
    public AjaxResult DeviceStatus() {

        // 设备在线离线状态只有pad端，所以从pad登录者信息查询
        Dispatch dispatch = padCommonUtil.getDispatch();
        Integer carID = dispatch.getCarID();
        QueryWrapper<CarDevice> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("carID", carID);
        List<CarDevice> list = carDeviceService.list(queryWrapper);
        // 通过redis
        final DeviceStatusDto deviceStatusDto = new DeviceStatusDto();
        if (null != list && !list.isEmpty()) {

            Map gatewayDeviceStateHash = myRedisTemplate.opsForHash().entries("gateway_device_state_hash");
            for (CarDevice item : list) {
                String serial = item.getSerial();
                String state = (String) gatewayDeviceStateHash.get(serial);

                if (item.getType().equals("1")) {
                    deviceStatusDto.setEcgStatus(changeStage(state));
                }

                if (item.getType().equals("2")) {
                    deviceStatusDto.setBrStatus(changeStage(state));
                }
            }
            // 超声不走网关，无法获取在线状态，则默认是离线状态
            deviceStatusDto.setUltStatus(0);
        }
        return AjaxResult.success(deviceStatusDto);
    }

    // 将redis的状态数据转成前面展示的数据
    public Integer changeStage(String stage) {

        if ("1".equals(stage)) {
            return 0;
        }
        if ("0".equals(stage)) {
            return 1;
        }
        return 0;
    }

    private NetWorkDto getNetWorkDto(Integer carId) {

        final NetWorkDto netWorkDto = new NetWorkDto();
        if (carId == 0) {

            // 没有的话就模拟
            Random random = new Random();
            netWorkDto.setSinr(String.valueOf(random.nextInt(100)));
            Integer randoms = random.nextInt(5);
            netWorkDto.setRssi(String.valueOf(randoms));
            netWorkDto.setRsrq(randoms <= 1 ? "差" : randoms <= 3 ? "中" : "优");
            netWorkDto.setBer(String.valueOf(random.nextInt(100)));
            netWorkDto.setDownlinkrate(String.valueOf(random.nextInt(1050)));
            netWorkDto.setUplinkrate(String.valueOf(random.nextInt(1050)));
            netWorkDto.setApn(String.valueOf(random.nextInt(100)));
            netWorkDto.setCarrier("中国联通");
            netWorkDto.setNetworkmode("WCDMA");
            netWorkDto.setCardmodel(String.valueOf(random.nextInt(100)));
            netWorkDto.setWorkingfrequency(String.valueOf(random.nextInt(4)));
            netWorkDto.setGatewayID("123456");
            netWorkDto.setGateInfo("网关信息");
            return netWorkDto;
        }

        Car byId = carService.getById(carId);
        String gatwayId = byId.getGatwayId();

        if (null != gatwayId && !gatwayId.isEmpty()) {
            /**
             * string sinr = 1; // 终端所在位置的信噪比
             *     string rssi = 2; // 终端接收信道强度
             *     string ber = 3; // 信道误比特率
             *     string rsrq = 4; // 参考信号接收质量
             *     string downlinkrate = 5; // 下行数据速率;
             *     string uplinkrate = 6; // 上行数据速率
             *     string apn = 7; // 建立承载的业务接入点名称
             *     string carrier = 8; // 运营商
             *     string networkmode = 9; // 使用5G上网卡上行时接入的网络类型，包括 WCDMA TDD-LTE FDD-LTE  FDD-NR
             *     string cardmodel = 10; // 使用上网卡型号
             *     string workingfrequency = 11; // WorkingFrequency 当前无线接入网络的工作频段
             *     string gatewayID = 12; //网关ID
             *     string gateInfo = 13; //网关信息
             *     int32 timestamp=14;
             *      1) "time"
             *  2) "2020-07-14 16:43:51"
             *  3) "apn"
             *  4) "3GNET"
             *  5) "sinr"
             *  6) "46"
             *  7) "rssi"
             *  8) "Excellent(-51)"
             *  9) "ber"
             * 10) "99"
             * 11) "rsrq"
             * 12) "22"
             * 13) "downlinkrate"
             * 14) "643"
             * 15) "uplinkrate"
             * 16) "40977"
             * 17) "cardmodel"
             * 18) "89860619110001576553"
             * 19) "carrier"
             * 20) "CHN-UNICOM"
             * 21) "networkmode"
             * 22) "4G(7)"
             * 23) "workingfrequency"
             * 24) "672"
             * 25) "gateInfo"
             * 26) ""
             *
             *
             *
             */

            Map<String, Object> entries = myRedisTemplate.opsForHash().entries("gateway_info_hash" + gatwayId);
            netWorkDto.setSinr(entries.get("sinr").toString());
            netWorkDto.setRsrq(entries.get("rsrq").toString());
            String rssi = entries.get("rssi").toString();
            // 处理网格
            // marginal的话就是一格，ok是两格，good是三格，excellent 是四格


            netWorkDto.setRssi(getNetGrid(rssi));
            netWorkDto.setBer(entries.get("ber").toString());
            String downlinkrate = entries.get("downlinkrate").toString();
            // bps
            netWorkDto.setDownlinkrate(downlinkrate + "bps");

            String uplinkrate = entries.get("uplinkrate").toString();

            netWorkDto.setUplinkrate(uplinkrate + "bps");
            netWorkDto.setApn(entries.get("apn").toString());
            String carrier = entries.get("carrier").toString();

            netWorkDto.setCarrier(getCarreier(carrier));
            String networkmode = entries.get("networkmode").toString();
            String substring = networkmode.substring(0, 2);
            netWorkDto.setNetworkmode(substring);
            netWorkDto.setCardmodel(entries.get("cardmodel").toString());
            netWorkDto.setWorkingfrequency(entries.get("workingfrequency").toString());
            netWorkDto.setGatewayID(gatwayId);
            netWorkDto.setGateInfo(entries.get("gateInfo").toString());

        }
        return netWorkDto;
    }

    private String getNetGrid(String s) {
        if (null == s) {
            return "1";
        }

        if (s.toLowerCase().equalsIgnoreCase("excellent")) {
            return "4";
        }

        if (s.toLowerCase().equalsIgnoreCase("good")) {
            return "3";
        }

        if (s.toLowerCase().equalsIgnoreCase("ok")) {
            return "2";
        }

        if (s.toLowerCase().equalsIgnoreCase("marginal")) {
            return "1";
        }


        return "1";
    }


    private String getCarreier(String s) {
// CHN-UNICOM ---> 联通， CHN-CT ---> 电信， CHINA MOBILE ---> 移动
        //  OTHER ---> 其他
        String u = "联通";
        String d = "电信";
        String c = "移动";
        if ("OTHER".equalsIgnoreCase(s)) {
            return "其他";
        }

        if ("CHN-UNICOM".equalsIgnoreCase(s)) {
            return u;
        }
        if ("CHINA MOBILE".equalsIgnoreCase(s)) {
            return c;
        }
        if ("CHN-CT".equals(s)) {
            return d;
        }

        return "其他";


    }


    // 判断网关类型
    private String getNetWorkType(String type) {
        String netMod_5 = "5G";
        String netMod_4 = "4G";
        String netMod_3 = "3G";

        if (type.equalsIgnoreCase("WCDMA")) {
            return netMod_3;
        }
        if (type.equalsIgnoreCase("FDD-LTE")) {

            return netMod_3;
        }
        if (type.equalsIgnoreCase("TDD-LTE")) {

            return netMod_3;
        }


        if (type.equalsIgnoreCase("LTE Advanced")) {

            return netMod_4;
        }

        if (type.equalsIgnoreCase("FDD-NR")) {

            return netMod_5;
        }

        if (type.equalsIgnoreCase("NR")) {

            return netMod_5;
        }


		/*
		Map<String, String> rlt = Maps.newConcurrentMap();
//		WCDMA TDD-LTE FDD-LTE  FDD-NR
		String carrier_l = "中国联通";
		String carrier_y = "中国移动";
		String carrier_d = "中国电信";

		String netMod_5 = "5G";
		String netMod_4 = "4G";
		String netMod_3 = "3G";

		if (type.equalsIgnoreCase("WCDMA"))
		{
			rlt.put("carrier", carrier_l);
			rlt.put("networkmode", netMod_3);
		}
		if (type.equalsIgnoreCase("FDD-LTE"))
		{
			rlt.put("carrier", carrier_l);
			rlt.put("networkmode", netMod_3);
		}
		if (type.equalsIgnoreCase("TDD-LTE"))
		{
			rlt.put("carrier", carrier_l);
			rlt.put("networkmode", netMod_3);
		}


		if (type.equalsIgnoreCase("LTE Advanced"))
		{
			rlt.put("carrier", carrier_l);
			rlt.put("networkmode", netMod_4);
		}

		if (type.equalsIgnoreCase("FDD-NR"))
		{
			rlt.put("carrier", carrier_l);
			rlt.put("networkmode", netMod_5);
		}

		if (type.equalsIgnoreCase("NR"))
		{
			rlt.put("carrier", carrier_l);
			rlt.put("networkmode", netMod_5);
		}
*/

        return "";
    }

    /**
     *         Random random = new Random();
     *         final NetWorkDto netWorkDto = new NetWorkDto();
     *         netWorkDto.setSinr(String.valueOf(random.nextInt(100)));
     *         Integer randoms = random.nextInt(5);
     *         netWorkDto.setRssi(String.valueOf(randoms));
     *         netWorkDto.setRsrq(randoms <= 1 ? "差" : randoms <= 3 ? "中" : "优");
     *         netWorkDto.setBer(String.valueOf(random.nextInt(100)));
     *         netWorkDto.setDownlinkrate(String.valueOf(random.nextInt(1050)));
     *         netWorkDto.setUplinkrate(String.valueOf(random.nextInt(1050)));
     *         netWorkDto.setApn(String.valueOf(random.nextInt(100)));
     *         netWorkDto.setCarrier("中国联通");
     *         netWorkDto.setNetworkmode("WCDMA");
     *         netWorkDto.setCardmodel(String.valueOf(random.nextInt(100)));
     *         netWorkDto.setWorkingfrequency(String.valueOf(random.nextInt(4)));
     *         netWorkDto.setGatewayID("123456");
     *         netWorkDto.setGateInfo("网关信息");
     */
}
